/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package simplepushserver;

import java.io.IOException;
import java.net.ServerSocket;
import javax.swing.JOptionPane;
import simplepushserver.gui.Notifier;

/**
 *
 * @author Filip
 */
public class PushServer implements Runnable{
    private int port;
    private boolean running=false;
    private ServerSocket ss;

    private Thread t;

    private SimpleLogger logger;
    private CommandHandler cHandler;
    private SettingsHandler sHandler;
    private Notifier notifyListener;

    public PushServer(SettingsHandler sHandler, SimpleLogger logger, Notifier listener){
        this.logger = logger;
        this.sHandler = sHandler;
        this.cHandler = new CommandHandler(sHandler,logger, listener);
        this.notifyListener = listener;
        this.port = sHandler.getServerPort();
    }

    public void run() {
        logger.log("127.0.0.1", "server", "started");
        t = new Thread("Server") {
            @Override
            public void run() {
                try {
                    ss = new ServerSocket(port);
                    running = true;
                    while (true) {
                        Listener l = new Listener(ss.accept(), cHandler);
                        l.start();
                    }
                } catch (Exception ex) {
                    String text = "Couldn't start server on port " + port;
                    if (running) {
                        text = "Error while listerning on port " + port;
                    }
                    text += "\n" + ex.toString();
                    JOptionPane.showMessageDialog(null, text);
                }
                running = false;
            }
        };
        t.start();
    }

    public void stop() {
        try {
            ss.close();
            t.interrupt();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        logger.log("127.0.0.1", "server", "stopped");
    }

    public void setPort(int port) {
        this.port = port;
        t.interrupt();
        start();
    }

    /**
     * @see PushServer.run();
     */
    public void start() {
        run();
    }
}
